package api

import (
	"context"
	"net/http"
	"sdc/repository/db/dao"
	"sdc/repository/db/model"
	"sdc/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

// AddFavorite 添加收藏
func AddFavorite(c *gin.Context) {
	userID := c.GetUint64("user_id")

	var req struct {
		ProjectID uint64 `json:"project_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewFavoriteService(db)
	// 检查项目是否存在且状态正常
	if !service.CheckProjectStatus(req.ProjectID) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "项目不存在或状态异常",
		})
		return
	}

	// 检查是否已收藏
	if service.IsFavorited(userID, req.ProjectID) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "已收藏该项目",
		})
		return
	}

	favorite := &model.Favorite{
		UserID:    userID,
		ProjectID: req.ProjectID,
	}

	if err := service.AddFavorite(favorite); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
}

// RemoveFavorite 取消收藏
func RemoveFavorite(c *gin.Context) {
	userID := c.GetUint64("user_id")
	favoriteID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewFavoriteService(db)
	// 检查是否是自己的收藏
	if !service.CheckFavoriteOwner(favoriteID, userID) {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg":  "无权限操作",
		})
		return
	}

	if err := service.RemoveFavorite(favoriteID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "取消收藏失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "取消收藏成功",
	})
}

// ListFavorites 收藏列表
func ListFavorites(c *gin.Context) {
	userID := c.GetUint64("user_id")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	// 支持按项目状态筛选
	status, _ := strconv.Atoi(c.DefaultQuery("status", "-1"))
	// 支持按分类筛选
	categoryID, _ := strconv.ParseUint(c.DefaultQuery("category_id", "0"), 10, 64)

	query := &service.FavoriteQuery{
		UserID:     userID,
		Status:     int8(status),
		CategoryID: categoryID,
		Page:       page,
		PageSize:   pageSize,
	}
	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewFavoriteService(db)

	favorites, total, err := service.ListFavorites(query)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取收藏列表失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": gin.H{
			"list":  favorites,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	})
}
